package com.demodis.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.UUID;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yang.test.TestInitBaseData;

public class Utils {
	private static String projectPath = TestInitBaseData.class.getResource("/").getPath().substring(1).replace("/", "\\").replace("WEB-INF\\classes", "baseData");
	private static Logger log = Logger.getLogger(Utils.class);

	/**
	 * 判断是否存在权限
	 * 
	 * @param permTotalValue
	 *            权限总值
	 * @param permValue
	 *            权限值
	 * @return
	 */
	public static boolean existPerm(int permTotalValue, int permValue) {
		permValue = (int) Math.pow(2, permValue);
		return (permTotalValue & permValue) == permValue;
	}
	
	public static void writeJson(Object object) {
		try {
			String json = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss", new SerializerFeature[0]);
			ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
			ServletActionContext.getResponse().getWriter().write(json);
			ServletActionContext.getResponse().getWriter().flush();
			ServletActionContext.getResponse().getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getChineseAbbr(String str) {
		HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();  
        outputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);  
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);  
        StringBuffer abbr = new StringBuffer();
        try {  
            for (int i = 0; str != null && i < str.length(); i++) {  
                String[] pins = PinyinHelper.toHanyuPinyinStringArray(str.charAt(i), outputFormat);
                if(pins != null && pins[0].length() > 0) {
                	abbr.append(pins[0].charAt(0));
                }
            }  
        } catch (BadHanyuPinyinOutputFormatCombination e) {  
            e.printStackTrace();  
        }  
		return abbr.toString();
	}

	public static boolean isPass(String actionName) {
		return (actionName.equals("permissionAction") || actionName.equals("roleAction") || actionName.equals("userAction") || actionName.equals("groupAction"));
	}

	/**
	 * 清空数据库里面所有表的数据
	 * @throws Exception 
	 */
	public static void truncate() throws Exception {
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps = null;

		String[] tableNames = new String[]{"tbl_contres", "tbl_detcontent", "tbl_detergroup", "tbl_deterperson"
				, "tbl_group", "tbl_model", "tbl_permission", "tbl_persduty"
				, "tbl_perssuggest", "tbl_position", "tbl_role", "tbl_user"};
		try {
			conn = DBUtil.getConnection();
			
			String sql;
			for(String name : tableNames) {
				sql = "TRUNCATE table " + name;
				log.info("清空表："+sql);
				ps = conn.prepareStatement(sql);
				ps.executeUpdate();
			}
			log.info("表清空完毕！");
		} catch (Exception e) {
			log.error("表清空失败！");
			throw new Exception();
		} finally {
			DBUtil.close(conn, ps, null);
		}
	}
	
	public static HSSFSheet getSheet(String excelName) throws Exception {
		POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(projectPath + excelName));
		HSSFWorkbook wb = new HSSFWorkbook(fs);
		return wb.getSheetAt(0);
	}
	
	public static String saveFile(File file, String fileName, String realPath) {
		fileName = UUID.randomUUID() + "."+ fileName.replace(".", ",").split(",")[1];
		
		File saveFile = new File(new File(realPath), fileName);
		if(!saveFile.getParentFile().exists()) {
			saveFile.getParentFile().mkdirs();
		}
		
		try {
			FileUtils.copyFile(file, saveFile);
		} catch (IOException e) {
			e.printStackTrace();
			new RuntimeException();
		}
		return fileName;
	}
}
